package com.wsj.a.collapsingdemo;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.wsj.a.collapsingdemo.utils.Config;
import com.wsj.library.slide.SwipeBackHelper;

import java.util.Stack;

import io.realm.Realm;

/**
 * Created by linxiujie on 2018/8/15.
 * TODO:应用
 */

public class App extends Application implements Application.ActivityLifecycleCallbacks {

    private static App mApp;

    public static App getInstance() {
        return mApp;
    }

    //管理activity的任务栈
    private Stack<Activity> mExistedActivitys = new Stack<>();

    //配置QQ,新浪微博和微信的key和value
    {
        PlatformConfig.setSinaWeibo(Config.WB_APP_KEY, Config.WB_APP_SECRET, Config.WB_CALLBACK_URL);
        PlatformConfig.setWeixin(Config.WX_APP_KEY, Config.WX_APP_SECRET);
        PlatformConfig.setQQZone(Config.QQ_APP_ID, Config.QQ_APP_KEY);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;

        //初始化数据库
        initRealm();
        //初始化友盟
        initUmeng();
        //管理所有的Activity
        registerActivityLifecycleCallbacks(this);

        debug();


        /**
         * 必须在 Application 的 onCreate 方法中执行 SwipeBackHelper.init 来初始化滑动返回
         * 第一个参数：应用程序上下文
         * 第二个参数：如果发现滑动返回后立即触摸界面时应用崩溃，请把该界面里比较特殊的 View 的 class 添加到该集合中，目前在库中已经添加了 WebView 和 SurfaceView
         */
        SwipeBackHelper.init(this, null);
    }

    private void initRealm() {
        //Realm初始化
        Realm.init(this);
        //数据库的配置
//        Realm.setDefaultConfiguration(RealmHelper.getInstance().getConfiguration());

    }


    private void debug() {

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        if (null != mExistedActivitys && null != activity) {
            // 把新的 activity 添加到最前面，和系统的 activity 堆栈保持一致
            mExistedActivitys.add(activity);
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if (null != mExistedActivitys && null != activity) {
            mExistedActivitys.remove(activity);
        }
    }


    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        Activity activity = mExistedActivitys.lastElement();
        return activity;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishLastActivity() {
        Activity activity = mExistedActivitys.lastElement();
        if (activity != null) {
            finishActivity(activity);
        }

    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            mExistedActivitys.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        Stack<Activity> activities = new Stack<>();
        //找到任务stack的activity
        for (Activity activity : mExistedActivitys) {
            if (activity.getClass().equals(cls)) {
                activities.add(activity);
            }
        }
        finishAllActivity(activities);
    }

    /**
     * 结束指定类名的Activity
     */
    public boolean hasActivity(Class<?> cls) {
        //找到任务stack的activity
        for (Activity activity : mExistedActivitys) {
            if (activity.getClass().equals(cls)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        finishAllActivity(mExistedActivitys);
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity(Stack<Activity> mExistedActivitys) {
        for (int i = 0, size = mExistedActivitys.size(); i < size; i++) {
            if (null != mExistedActivitys.get(i)) {
                mExistedActivitys.get(i).finish();
            }
        }
        mExistedActivitys.clear();
    }


    /**
     * 退出应用程序
     */
    public void exit() {
        try {
            finishAllActivity();
            System.exit(0);
        } catch (Exception e) {
        }
    }

    //获取版本名
    public static String getVerisonName() {
        return getPackageInfo(App.getInstance()).versionName;
    }

    //版本号
    public static int getVersionCode() {
        return getPackageInfo(App.getInstance()).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    private void initUmeng() {

        /**
         * 初始化common库
         * 参数1:上下文，不能为空
         * 参数2:【友盟+】 AppKey
         * 参数3:【友盟+】 Channel
         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         * 参数5:Push推送业务的secret
         */
        UMConfigure.init(this, "5b73e680f43e4808f9000113", "Umeng", UMConfigure.DEVICE_TYPE_PHONE,"");

        UMShareAPI.get(this);
        /**
         * 每次授权都想调起授权页怎么操作
         * http://bbs.umeng.com/thread-25545-1-1.html?spm=a311a.9588098.0.0
         * 注意：最新版本微信客户端调用接口后也不再出现授权确认页面，确认在微信客户端切换账号后，再次调用登录接口获取的用户资料变化即可
         *
         * 在6.3之后使用下面代码处理其他平台
         */
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);
    }
}